/**
 * 渲染进程日志工具
 * 将日志通过IPC发送到主进程进行统一管理
 */

interface LogMeta {
  [key: string]: unknown
}

interface Logger {
  debug: (message: unknown, meta?: LogMeta) => void
  info: (message: unknown, meta?: LogMeta) => void
  warn: (message: unknown, meta?: LogMeta) => void
  error: (message: unknown, meta?: LogMeta) => void
  success: (message: unknown, meta?: LogMeta) => void
}

class RendererLogger implements Logger {
  private sendLog(level: string, message: unknown, meta?: LogMeta): void {
    // 如果message是对象，转换为字符串
    const logMessage = typeof message === 'object' ? JSON.stringify(message) : String(message)
    try {
      // 发送日志到主进程
      window.electron?.ipcRenderer?.send('log', { level, message: logMessage, meta })

      // 同时发送到 LogPanel（如果存在）
      const logEvent = new CustomEvent('renderer-log', {
        detail: { level, message: logMessage, meta }
      })
      window.dispatchEvent(logEvent)

      // 同时在控制台输出（开发环境）
      if (process.env.NODE_ENV === 'development') {
        const logMethod =
          level === 'error'
            ? console.error
            : level === 'warn'
              ? console.warn
              : level === 'debug'
                ? console.debug
                : console.log

        const metaStr = meta ? ` ${JSON.stringify(meta)}` : ''
        logMethod(`[RENDERER] [${level.toUpperCase()}]: ${logMessage}${metaStr}`)
      }
    } catch {
      // 如果IPC不可用，降级到控制台输出
      console.log(`[RENDERER] [${level.toUpperCase()}]: ${logMessage}`, meta)
    }
  }

  debug(message: unknown, meta?: LogMeta): void {
    this.sendLog('debug', message, meta)
  }

  info(message: unknown, meta?: LogMeta): void {
    this.sendLog('info', message, meta)
  }

  warn(message: unknown, meta?: LogMeta): void {
    this.sendLog('warn', message, meta)
  }

  error(message: unknown, meta?: LogMeta): void {
    this.sendLog('error', message, meta)
  }

  success(message: unknown, meta?: LogMeta): void {
    this.sendLog('info', message, meta)
  }
}

// 创建日志实例
const logger = new RendererLogger()

export default logger
